//
//  MobilePhoneChargeIndexViewController.m
//  ELife
//
//  Created by  刘奇男 on 11-6-14.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "MobilePhoneChargeIndexViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "AlertView.h"
#import "ELifeAppDelegate.h"
#import "MobilePhoneChargeConfirmViewController.h"
#import "GDataXMLNode.h"
#import "GTMBase64.h"
#import "GetMyData.h"
#import "LoginController.h"

@implementation MobilePhoneChargeIndexViewController

@synthesize phoneNumber, phoneNumberPlace, costBackView, costTextField, numberBackView,phonePlace,constList,choseCost,costPicker;

- (void)requestCost
{
    
    NSString* userid = [GetMyData getUserId];
    
    if (userid == nil) {
        LoginController* lc = [[LoginController alloc] init:self];
        [self.navigationController pushViewController:lc animated:YES];
        [lc release];
        return;
    }
    
    [[ELifeAppDelegate App] showProgressDialog:@"请稍候"];
    
    
    /**
     action  => get_phoneinfo
     user_id =>用户id
     phone =>手机号
     */
    
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"phonepay.php?"]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:3];
    [param setObject:@"get_phoneinfo" forKey:@"action"];
    [param setObject:userid forKey:@"user_id"];
    [param setObject:phoneNumber.text forKey:@"phone"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[[ELifeAppDelegate App] httpRequestPoint]openUrl:dic postParam:param target:self];
    
    [param release];
}
#pragma mark -
#pragma mark 联网回调
- (void)iRequestFinished:(NSData *)response
{    
    [[ELifeAppDelegate App] hideProgressDialog];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    
//    NSLog(@"PhoneCharge------%@\n", doc);
    GDataXMLElement* rootElement = [doc rootElement];    
    NSLog(@"rootElement------%@\n", rootElement);
    
    GDataXMLElement* headsElement = [[rootElement elementsForName:@"head"]objectAtIndex:0];
   
    GDataXMLNode* returnCode = [[headsElement elementsForName:@"returncode"] objectAtIndex:0];
    
    NSInteger code = [[returnCode stringValue] intValue];
    if (code == -105){
        //        [AlertView showAlert:@"请先登录" action:@"goLogin"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录"
                                                       delegate:self cancelButtonTitle:@"取消" otherButtonTitles: @"确定", nil];
        [alert setTag:11];
        [alert show];
        [alert release];
        return;
    } else if (code != 0 ){
        [AlertView showAlert:@"获取信息失败"];
        return;
    }
    
    
//    <body><user_id>6</user_id><type>北京移动</type><phone>13911500504</phone><moneys><money>30</money><money>50</money><money>100</money><money>200</money><money>300</money><money>500</money></moneys></body>    
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];  
    NSLog(@"bodyElement------%@\n", bodyElement);
    
    NSString* place = [[[bodyElement elementsForName:@"type"] objectAtIndex:0] stringValue];
    self.phonePlace = place;
    [self.phoneNumberPlace setText:place];
    //某个具体节点的文本内容
    GDataXMLElement* moneysElement = [[bodyElement elementsForName:@"moneys"]objectAtIndex:0];
    
    NSLog(@"moneysElement: %@",moneysElement );
    
    NSArray *items = [moneysElement elementsForName:@"money"];    
    self.constList =  [[NSMutableArray alloc] initWithCapacity:[items count]];
    
    for (int i = 0; i < [items count]; i ++)
    {
        GDataXMLElement *element = [items objectAtIndex:i];
        
        NSString* name = [element stringValue];
//        NSLog(@"name: %@", name);
        [constList addObject: name];
        
        if (i == 0)
        {
            [costTextField setText:name];
        }
    }
    
    [doc release];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [phoneNumber release];
    [phoneNumberPlace release];
    [costBackView release];
    [costTextField release];
    [numberBackView release];
    [constList release];
    [choseCost release];
    [costPicker release];
    [super dealloc];
    
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self.navigationItem setTitle:@"手机充值"];
    
    
    costBackView.layer.cornerRadius = 8;
    costBackView.layer.masksToBounds = YES;
    
    numberBackView.layer.cornerRadius = 8;
    numberBackView.layer.masksToBounds = YES;
    
    UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init];
	temporaryBarButtonItem.title = @"返回";
	self.navigationItem.backBarButtonItem = temporaryBarButtonItem;
	[temporaryBarButtonItem release];
    
    [phoneNumber setDelegate:self];
    [costTextField setDelegate:self];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(IBAction) nextStep:(id)sender
{
    
    [phoneNumber resignFirstResponder];
    [costTextField resignFirstResponder];
    
    if ([phoneNumber.text length] == 0){
        
        [AlertView showAlert:@"请填写手机号码"];
        return;
    }
    [self requestCost];
    
}

-(IBAction) payNow:(id)sender
{
    
    [phoneNumber resignFirstResponder];
    [costTextField resignFirstResponder];
    
    if (constList == nil || [constList count] == 0)
    {
        [AlertView showAlert:@"请先进行下一步"];
        return;
    }
    
    MobilePhoneChargeConfirmViewController *controller = [[MobilePhoneChargeConfirmViewController alloc] initWithNibName:@"ChargeConfirmView" bundle:nil];
    
    [self.navigationController pushViewController:controller animated:YES];
    
    
    [controller setUserType:costTextField.text];
    [controller setUserPhoneNumber:phoneNumber.text];
    
    [controller release];
}

-(IBAction) resetNumber:(id)sender
{
    
    [phoneNumber resignFirstResponder];
    [costTextField resignFirstResponder];
    
    [phoneNumber setText:@""];
    [phoneNumberPlace setText:@""];
    [costTextField setText:@""];
    
    [constList release];
    constList = nil;
}

-(IBAction) back:(id)sender
{
    
    [phoneNumber resignFirstResponder];
    [costTextField resignFirstResponder];
    
    [self.navigationController popToViewController:self animated:YES];
}
-(void) costPickerViewAppare
{
    [self.view addSubview:choseCost];
}

-(IBAction) closeKeyPad:(id)sender
{
    [phoneNumber resignFirstResponder];
    [costTextField resignFirstResponder];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if([alertView tag] == 11)
    {
        if (buttonIndex == 1){
            LoginController *controller = [[LoginController alloc] initWithNibName:@"LoginController" bundle:nil];
            
            [self.navigationController pushViewController:controller animated:YES];
            [controller release];
        }
        return; 
        
    }
}


- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField != costTextField){
        return;
    } 
    
    [phoneNumber resignFirstResponder];
    [costTextField resignFirstResponder];
    
    [self costPickerViewAppare];
}


- (IBAction) choseCost:(id)sender
{
    [choseCost removeFromSuperview];
    
    NSString* cost = [constList objectAtIndex:[costPicker selectedRowInComponent:0]];
    
    [costTextField setText:cost];
}

- (IBAction) hideChoseCost:(id)sender
{
    [choseCost removeFromSuperview];
}


#pragma mark -
#pragma mark UIPickerViewDataSource

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{			
	return [constList objectAtIndex:row];
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
	CGFloat componentWidth = 0.0;
    
    componentWidth = 280;
    
	return componentWidth;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
	return 40.0;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	return [constList count];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 1;
}
@end
